<?php

class Sgit_Util_Regresion
{
 
 
    static public function run($data,$f_ini=null)
    {
        $keys=array_keys($data);
        $f_ini=new Zend_Date($keys[0],Zend_Date::ISO_8601);
               
        $q=0;
        foreach($data as $v) $y[$q++]=round($v,2);
        
        
        
        $otherarray = $y; //Y-array
        $sumX = 0;
        $sumY = 0;
        $sumXX = 0;
        $sumXY = 0;
        $n = count($otherarray); //number of items
    
        for ($i = 1; $i <= $n; $i++) {
            $myarray[] = $i;
        }

    
        for ($i = 0; $i < $n; $i++) {
            $sumX += $myarray[$i];
            $sumY += $otherarray[$i];
            $meanX = $sumX / $n;
            $meanY = $sumY / $n;
            $sumXX += pow($myarray[$i], 2);
            $sumXY += ($myarray[$i]) * ($otherarray[$i]);
            $m = ($sumXY - $meanY * $sumX) / ($sumXX - $meanX * $sumX);
            $b = $meanY - $meanX * $m;
        }
    
    

    
        for ($i = 0; $i < $n; $i++) {
            $data_pasado[] = round($m * $i + $b,2);
        }
          

        $ajuste=($y[count($y)-1] - $data_pasado[$n-1]);
    
    

        for ($i = $n; $i < $n+count($y)+24; $i++) {
            $data_futuro[] =round( $m * $i + $b,2);
        }
        
        

        $regresion1=array_merge($data_pasado,$data_futuro);

        foreach($regresion1 as $v) $regresion2[] =round($v+$ajuste,2);
        
        $maxfecha=date('Y-m-d',strtotime('+23 month'));
        
        foreach($regresion1 as $k => $v){

            $fecha=$f_ini->get('yyyy-MM-dd');
            if($fecha > $maxfecha) continue;
            $regre1[$fecha]=$v;
            $regre2[$fecha]=$regresion2[$k];
            $f_ini->addMonth(1);
        }
        
        foreach($regre1 as $k=>$v){
            $sal_regre1[$k]=$data[$k] ?  round($data[$k],2) : $v;
            $sal_regre2[$k]=$data[$k] ?  round($data[$k],2) : $regre2[$k];
            $data[$k]=$data[$k] ? round($data[$k],2) : null;
        }
        


        return array(
        'original'=>$data,
        'regresion'=>$regre1,
        'regresion_ajuste'=>$regre2,
        'salida_regresion'=>$sal_regre1,
        'salida_regresion_ajuste'=>$sal_regre2,
        );
        return $salida;
        
    
    }
}